package com.example.barry.udpdemo.Service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.example.barry.udpdemo.MainActivity;

import org.json.JSONObject;

import java.net.DatagramPacket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by barry on 17-2-20.
 */

public class UDFClient extends Service{



    public IBinder onBind(Intent intent){
        return null;
    }

    final Intent intent = new Intent();
    public   MulticastSocket ds;// client
    public   String multicastHost="224.0.0.255";
    public  InetAddress receiveAddress;
    public void onCreate  (){
        super.onCreate();
        intent.setAction(MainActivity.ACTION_UPDATEUI);
        try {
                ds = new MulticastSocket(40000);
                receiveAddress= InetAddress.getByName(multicastHost);
                ds.joinGroup(receiveAddress);
                ReceviceThread rt = new ReceviceThread();
                rt.start();
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
    }


 private  class ReceviceThread extends Thread{
        public void run() {
            // TODO Auto-generated method stub
            final byte buf[] = new byte[1024];
          final    DatagramPacket dp = new DatagramPacket(buf, 1024);
            while (true) {
                try {
                    ds.receive(dp);
                    Log.i("sddsds","123");
                    System.out.println("client ip : "+new String(buf, 0, dp.getLength()));
                    String temp = new String(buf,0,dp.getLength());
                    JSONObject jsonObject = new JSONObject(temp);

                  /*  put("IP","123")
                            .put("deviceID","234")
                            .put("shopfloorID","2345");*/
                    intent.putExtra("IP",jsonObject.getString("IP"));
                    intent.putExtra("deviceID",jsonObject.getString("deviceID"));
                    intent.putExtra("shopfloorID",jsonObject.getString("shopfloorID"));
                    sendBroadcast(intent);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
